package com.blockmeta.bbs.immodule.activity.chat;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.baselibrary.net.callback.BaseResponseCallBack;
import com.blockmeta.bbs.baselibrary.utils.UUIDUtil;
import com.blockmeta.bbs.businesslibrary.arouter.RouterConstant;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseImResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.umeng.dialog.BlockMessageShareData;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.util.RouterActivityHelper;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.adapter.ChatAdapter;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.corebean.IMMetaBase;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.dao.ChatMessage;
import com.blockmeta.bbs.immodule.dao.ChatMessageBuilder;
import com.blockmeta.bbs.immodule.dao.IMUserEntity;
import com.blockmeta.bbs.immodule.eventbus.UserInfoChangeEvent;
import com.blockmeta.bbs.immodule.net.api.GetIsShieldApi;
import com.blockmeta.bbs.immodule.widget.TempRelationBar;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

/**
 * Created by author on 2019/3/25.
 * 个人聊天页面
 */
@Route(path = RouterPath.IM_UUChatActivity_ACTIVITY,extras = RouterConstant.EXTRAL_LOGIN)
public class UUChatActivity extends BaseChatActivity {
    //arouter注入bug，只能在子类
    @Autowired(name = Constant.ZERO)
    public String ZeroParam;

    @BindView(R2.id.llayout_temprelation_action)
    TempRelationBar mTempRelationBar;


    @Override
    protected void initialize() {

        super.initialize();

        mIvFriendOrCircleIcon.setImageResource(R.drawable.icon_friend);
        BindUserData();
    }

    @Override
    protected long getUserIdFromBundle() {
        if (!TextUtils.isEmpty(ZeroParam)) {
            return Long.parseLong(ZeroParam);
        } else {
            return getIntent().getLongExtra(Params.USER_TAG, 0);
        }
    }

    private void BindUserData() {
        bindTempRelationBar();
        getUserDataAndBind();
    }

    /**
     * 根据好友关系判断是否显示加为好友功能
     */
    private void bindTempRelationBar() {
        mTempRelationBar.onInitialize(toUserId, new TempRelationBar.ITempRelationBarCallBack(){

            @Override
            public void shieldSuccess(boolean shield) {
                if(shield){
                    //添加两条提示信息到列表并显示,因为下次进来不显示就不保存数据库，添加两个递增的id
                    long lastMsgId = 0;
                    if(mChatAdapter.getData().size() > 0){
                        lastMsgId = mChatAdapter.getItem(mChatAdapter.getData().size() - 1).getId();
                    }

                    ChatMessage notifyMsg = ChatMessageBuilder.buildNotifyMsg(lastMsgId + 1, "已屏蔽该用户"
                            , UUIDUtil.uuid(), toUserId, AccountHelper.getUidInt(), ChatMessage.MSG_TYPE_UU);
                    ChatMessage notifyMsg1 = ChatMessageBuilder.buildNotifyMsg(lastMsgId + 2, "可在个人中心设置取消屏蔽"
                            , UUIDUtil.uuid(), toUserId, AccountHelper.getUidInt(), ChatMessage.MSG_TYPE_UU);
                    mChatAdapter.addData(notifyMsg);
                    mChatAdapter.addData(notifyMsg1);
                    scrollToEndNoSmooth();

                }
                Map<String, String> notifyMap = new HashMap<>(1);
                notifyMap.put("shield", String.valueOf(shield));
                IMApplicationContext.getIMMetaService().post(new UserInfoChangeEvent(toUserId, notifyMap));
            }
        });
        boolean isFriend = IMApplicationContext.getUserDomainService().isFriend(toUserId);
        if (!isFriend) {
            IMApplicationContext.getIMMetaService().post(new IMMetaBase.Event_MayBeTempTalkAdd());
            mTempRelationBar.setVisibility(View.VISIBLE);
            RetrofitFactory.getRetrofit().create(GetIsShieldApi.class)
                    .isShield(toUserId)
                    .compose(RxUtil.<BaseImResponse<Object>>rxSchedulerHelper())
                    .compose(RxUtil.<Object>commonResult())
                    .compose(((RxAppCompatActivity) mContext).<Object>bindToLifecycle())
                    .subscribe(new CommonSubscriber<Object>(mContext) {
                        @Override
                        public void onNext(Object o) {
                            if (o != null && o instanceof Boolean) {
                                mTempRelationBar.setShieldStatus((Boolean)o);
                            }
                        }
                    });

        }
    }




    /**
     * 获取对方信息并绑定
     */
    private void getUserDataAndBind() {
        IMApplicationContext.getUserDomainService().getUser(toUserId, false, new BaseResponseCallBack<String, IMUserEntity>() {
            @Override
            public void fail(String msg) {
            }

            @Override
            public void success(IMUserEntity IMUserEntity) {
                mUser = IMApplicationContext.getUserDomainService().getUser(toUserId, Params.USER_PERSON);
                bindUserData();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mIsCreate) {
            mIsCreate = false;
        } else {
            //回到页面时需要更新名称
            getUserDataAndBind();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_AddFriends event){
        //添加好友，判断是否是当前用户，需要隐藏上面的陌生人框
        relationBarStatusChange();
    }

    private void relationBarStatusChange() {
        boolean isFriend = IMApplicationContext.getUserDomainService().isFriend(toUserId);
        if(isFriend){
            mTempRelationBar.setVisibility(View.GONE);
        }else {
            mTempRelationBar.setVisibility(View.VISIBLE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.Event_DeleteFriends event){
        //添加好友，判断是否是当前用户，需要隐藏上面的陌生人框
        relationBarStatusChange();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IMMetaBase.EventShieldFriend event){
        //屏蔽和解除屏蔽好友
        mTempRelationBar.setShieldStatus(event.isShield);
    }



    private void bindUserData() {
        mTvTitle.setText(TextUtils.isEmpty(mUser.getRemarkName()) ? mUser.getName() : mUser.getRemarkName());
    }




    @Override
    void jumpToFriendOrCircleHome() {
        RouterActivityHelper.openUserCenter(mContext, String.valueOf(toUserId));
    }

    @Override
    protected int getChatType() {
        return ChatMessage.MSG_TYPE_UU;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
